<template>
  <basic-dialog
    :visible="show"
    minWidth="900px"
    :title="`阈值${this.statusList[4].label}设置`"
    :isShowClose="true"
    :isFullScreen="false"
    :isShowBasicFooter="false"
    @close="$emit('close')"
    :loading="isSubmitting"
  >
    <div class="btn-area">
      <q-form>
        <q-btn
          unelevated
          outline
          color="primary"
          @click="addRule"
        >新增
        </q-btn>
        <q-btn-dropdown label="导出Excel" style="padding: 0px 10px" class="margin-l-20" unelevated outline color="primary">
          <q-list dense>
            <q-item clickable v-close-popup class="no-padding"
                    @click="exportExcelNew(processData.id)">
              <q-item-section>
                <q-item-label style="padding-left:15px">导出当前设备</q-item-label>
              </q-item-section>
            </q-item>
            <q-item clickable v-close-popup class="no-padding"
                    @click="exportExcelNew()">
              <q-item-section>
                <q-item-label style="padding-left:15px">导出全部设备</q-item-label>
              </q-item-section>
            </q-item>
          </q-list>
        </q-btn-dropdown>
      </q-form>

    </div>
    <div class="padding-20">
      <q-table
        id="thresholdSetTable"
        :data="tableData"
        :columns="columns"
        hide-bottom
        class="myTable scroll stick-last-col"
        separator="cell"
        no-data-label="暂无数据"
        :pagination="{ rowsPerPage: 0 }"
        color="primary"
      >
        <template v-slot:no-data>
          <div
            class="full-width row flex-center font-size-14"
            style="color: #999"
          >
            暂无数据
          </div>
        </template>
        <template v-slot:header-cell-duration="props">
          <q-th>
            {{ props.col.label }}
            <q-icon
              name="iconfont icontubiao-72"
              class="font-18 text-grey"
              style="margin-left: 1px"
            >
              <q-tooltip
                >持续时长：持续时长为0，指参数的值达到阈值判断条件时，立刻触发报警；持续时长不为0，指参数的值达到阈值判断条件且持续时长满足设定条件，才会触发报警</q-tooltip
              >
            </q-icon>
          </q-th>
        </template>
        <template v-slot:header-cell-frequency="props">
          <q-th>
            {{ props.col.label }}
            <q-icon
              name="iconfont icontubiao-72"
              class="font-18 text-grey"
              style="margin-left: 1px"
            >
              <q-tooltip
                >消息推送频率：在此时间段内，无论触发多少次报警，只推送一次消息（避免因频繁报警，导致频繁的消息推送）</q-tooltip
              >
            </q-icon>
          </q-th>
        </template>
        <template v-slot:body-cell-id="{ row }">
          <q-td>
            <label>{{ row.__index + 1 }}</label>
          </q-td>
        </template>
        <template v-slot:body-cell-label="{ row }">
          <q-td>
            <label>{{ row.judgementMethod == 1 && row.label || "" }}</label>
          </q-td>
        </template>
        <template v-slot:body-cell-pointCondition="{ row }">
          <q-td>
            <label v-if=" row.judgementMethod === 1 ">{{
             row.yzOperator && row.yzOperator.getDisplayString()
            }}</label>
            <label v-if="row.judgementMethod === 4">{{
              row.el
            }}</label>
          </q-td>
        </template>
        <template v-slot:body-cell-duration="{ row }">
          <q-td>
            <div class="flex">
              <label> {{ row.duration && row.duration + 's' }}</label>
            </div>
          </q-td>
        </template>
        <template v-slot:body-cell-frequency="{ row }">
          <q-td>
            <div class="flex">
              <label> {{ frequencyStrs[row.frequency] }}</label>
            </div>
          </q-td>
        </template>
        <template v-slot:body-cell-operations="props">
          <q-td class="operations" style="width: 100px">
            <q-btn
              flat
              dense
              round
              color="primary"
              icon="iconfont icontubiao-12"
              @click="editRule(props.row)"
            >
              <q-tooltip>编辑</q-tooltip>
            </q-btn>
            <q-btn
              flat
              dense
              round
              color="primary"
              icon="iconfont icontubiao-16"
              @click="deleteRule(props.row)"
            >
              <q-tooltip>删除</q-tooltip>
            </q-btn>
          </q-td>
        </template>
      </q-table>
    </div>
    <plcThresholdSetDialog
      :show="plcThresholdSetDialogOpenFlag"
      :selectedLabels="selectedLabels"
      @close="closeThresholdDialog"
      :nameOptions="nameOptions"
      :editRuleFlag="editRuleFlag"
      v-model="model"
      @submit="submit"
    />
  </basic-dialog>
</template>

<script>
import XLSX from 'xlsx'
import { deletePlcSet, getListPlcWarnKey, getPlcWarnSet, setPlcWarnSet, exportPlcWarnExcel } from 'src/boot/status-monitor/machine'
import plcThresholdSetDialog from './plc-threshold-set-dialog'
import { mapGetters } from 'vuex'
import { map2Operator, execOperator } from 'src/boot/common/operatorUtils'
import exportJs from 'src/pages/statistics/components/export'

export default {
  name: 'plc-threshold-set-pannel',
  components: { plcThresholdSetDialog },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    processData: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      isSubmitting: false,
      plcThresholdSetDialogOpenFlag: false,
      exportLoading: false,
      tableData: [],
      nameOptions: [],
      frequencyStrs: { '0': '全部推送', '60': '1分钟/次', '180': '3分钟/次', '300': '5分钟/次', '600': '10分钟/次', '1800': '30分钟/次' },
      columns: [
        { name: 'id', label: '序号', align: 'center', field: 'id' },
        { name: 'alarmName', label: '报警名称', align: 'center', field: 'alarmName' },
        { name: 'label', label: '参数', align: 'center', field: 'label' },
        {
          name: 'pointCondition',
          label: '判断条件',
          align: 'center',
          field: 'pointCondition'
        },
        {
          name: 'duration',
          label: '持续时长',
          align: 'center',
          field: 'duration'
        },
        {
          name: 'frequency',
          label: '消息推送频率',
          align: 'center',
          field: 'frequency'
        },
        { name: 'operations', label: '操作', align: 'center', field: 'operations' }
      ],
      model: this.initialModel(),
      editRuleFlag: false
    }
  },
  computed: {
    ...mapGetters([
      'userInfo', 'statusList', 'client'
    ]),
    selectedLabels () {
      if (this.tableData) {
        return this.tableData.map(d => d.label)
      }
      return null
    }
  },
  watch: {
    show (val) {
      if (val) {
        this.getPlcWarn()
      }
    }
  },
  methods: {
    editRule (row) {
      this.editRuleFlag = true
      this.model = JSON.parse(JSON.stringify(row))
      this.plcThresholdSetDialogOpenFlag = true
    },
    execOperator (data, op) {
      return execOperator(data, op)
    },
    initialModel () {
      return {
        judgementMethod: 1,
        alarmName: null,
        label: null,
        pointCondition: 1,
        duration: 0,
        frequency: 5 * 60,
        avalue: null,
        bvalue: null,
        yzOperator: null
      }
    },
    // 提交数据
    async submit (data) {
      data.deviceId = this.processData.id
      this.isSubmitting = true
      try {
        await setPlcWarnSet([data])
        this.$message.success('操作成功')
        this.initPlcWarnSet()
      } finally {
        this.isSubmitting = false
      }
    },
    // 是否显示a输入框
    showA (row) {
      const aArr = [1, 4, 6, 7, 9, 10, 11, 12, 13, 14, 15]
      return aArr.indexOf(row.pointCondition) > -1
    },
    // 是否显示B输入框
    showB (row) {
      const bArr = [1, 5, 6, 10, 11, 12, 13, 14, 15]
      return bArr.indexOf(row.pointCondition) > -1
    },
    // 获取plc阈值名称下拉框
    getPlcWarn () {
      this.initPlcWarnKey()
      this.initPlcWarnSet()
    },
    async initPlcWarnKey () {
      let res = await getListPlcWarnKey(this.processData.id)
      if (res?.data?.length > 0) {
        this.nameOptions = res.data.map(item => {
          return {
            ...item,
            value: item.label
          }
        })
      }
    },
    async initPlcWarnSet () {
      // 获取已经设置的表格数据
      const params = {
        deviceId: this.processData.id,
        tenantId: this.userInfo.tenant_id
      }
      let res = await getPlcWarnSet(params)
      this.tableData = res.data.map(item => {
        return {
          ...item,
          yzOperator: map2Operator(item.pointCondition, item.label, item.avalue, item.bvalue, item.yzOperator)
        }
      })
    },
    // 添加一条数据
    addRule () {
      this.editRuleFlag = false
      this.model = this.initialModel()
      this.plcThresholdSetDialogOpenFlag = true
    },
    closeThresholdDialog () {
      this.plcThresholdSetDialogOpenFlag = false
    },
    // 删除数据
    deleteRule (row) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>确认删除该条信息吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(async () => {
        await deletePlcSet(row.id)
        this.initPlcWarnSet()
      })
    },
    /**
    * 导出excel
    */
    exportExcel () {
      this.exportLoading = true
      let workbook = document.querySelector('#thresholdSetTable')
      let sheet = XLSX.utils.table_to_sheet(workbook, { raw: true })
      sheet['!ref'] = `A1:F${this.tableData.length + 1}`
      try {
        exportJs.openDownloadDialog(exportJs.sheet2blob(sheet), '阈值设置.xlsx')
        this.exportLoading = false
      } catch (error) {
        console.log(error)
      }
    },
    exportExcelNew (deviceId) {
      this.$q.loading.show()
      let data = {}
      if (deviceId) {
        data.deviceId = deviceId
      }
      const params = [{ name: '' }]
      const res = this.$getUploadPath(params, '')
      this.requestId = res.fileNameNew
      data['requestId'] = res.fileNameNew
      this.onSubscribe()
      return exportPlcWarnExcel(data).then(res => {
        if (res.code !== '1200') {
          this.$showErrTips('导出异常，请稍后重试')
          this.closeUbscribeTopic()
        }
      }).catch(res => {
        console.log(res)
        this.closeUbscribeTopic()
      })
    },
    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.requestId}`, this.onMessageArrived, { id: `${this.requestId}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    closeUbscribeTopic () {
      this.client.unsubscribe(`${this.requestId}`)
      this.$q.loading.hide()
    },
    async onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.requestId) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('导出异常，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      await this.$saveFileForBlob(msg.data, '阈值设置.xls')

      this.closeUbscribeTopic()
      this.$message.success('数据请求成功,请保存文件')
    }
  }
}
</script>

<style scoped lang="scss">
.add-wrapper {
  width: 100%;
  height: 48px;
  background: #f3f3f3;
  border-radius: 0px 0px 6px 6px;
  font-size: 14px;
  font-weight: 500;
  color: #5f77fd;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.btn-area {
  margin-left: 20px;
  margin-top: 20px;
  button {
    min-width: 96px;
    height: 32px;
  }
}
</style>
